package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.TransportUserCardDTO;
import com.hunttown.mes.rpc.domain.TransportUserCardLogDTO;
import com.hunttown.mes.rpc.domain.TransportUserDTO;
import com.hunttown.mes.rpc.domain.enums.pay.ReceiveWayEnum;
import com.hunttown.mes.rpc.domain.enums.pay.RechargeTypeEnum;
import com.hunttown.mes.rpc.domain.query.TransportUserCardDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportUserCardLogDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportUserDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import com.hunttown.mes.manage.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * @title: 会员卡
 * @author: wangjunfu
 * @date: 2019-07-06 10:58:53
 * @description:
 */
@Controller
@RequestMapping(value = "/basic/usercard")
public class UserCardController {

    private final static Logger logger = LoggerFactory.getLogger(UserCardController.class);

    private final AnalysisManageManageService manageService;
    private final ASendSmsManageService smsSendService;
    private final TransportUserCardManageService userCardService;
    private final TransportUserManageService userService;
    private final TransportUserCardLogManageService cardLogService;
    private final TransportOperateLogManageService logService;
    private final ModelService modelService;

    @Autowired
    public UserCardController(TransportUserCardManageService userCardService, AnalysisManageManageService manageService, ASendSmsManageService smsSendService, ModelService modelService, TransportUserManageService userService, TransportUserCardLogManageService cardLogService, TransportOperateLogManageService logService) {
        this.userCardService = userCardService;
        this.manageService = manageService;
        this.smsSendService = smsSendService;
        this.modelService = modelService;
        this.userService = userService;
        this.cardLogService = cardLogService;
        this.logService = logService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return vm
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, TransportUserCardDTOQuery dtoQuery) {

        // 通过真实姓名搜索
        if (StringUtils.isNotBlank(dtoQuery.getTrueName())) {
            TransportUserDTO userDTO = userService.getByTrueName(dtoQuery.getTrueName());
            if (userDTO != null) {
                dtoQuery.setUserId(userDTO.getId());
            }
        }

        // 通过用户id 搜索
        if (dtoQuery.getUserId() != null && dtoQuery.getUserId() > 0) {
            TransportUserDTO userDTO = userService.getFromCacheId(dtoQuery.getUserId());
            if (userDTO != null) {
                dtoQuery.setTrueName(userDTO.getTrueName());
            }
        }

        dtoQuery.setOrderBy("order by id desc");
        Page<TransportUserCardDTO> dataPage = userCardService.getForPage(dtoQuery);

        // 实时更新列表信息
        if (dataPage != null && dataPage.getItems().size() > 0) {
            for (TransportUserCardDTO item : dataPage.getItems()) {
                item.setTrueName(modelService.getUserTrueName(item.getUserId()));
            }
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        //region 页面按钮权限
        String pin = AdminBaseClass.getPin(request);

        //编辑、删除
        String[] menus = {"Y-Y-HYK-BJ", "Y-Y-HYK-SC", "Y-Y-HYK-QTY", "Y-Y-HYK-CZ"};
        model.addAttribute("Permission", manageService.GetBtnPermission(menus, pin));
        //endregion

        return "basic/usercard/index";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model  model模型
     * @param id     主键id
     * @param userId 会员id
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id, Integer userId) {
        id = (id == null ? 0 : id);
        userId = (userId == null ? 0 : userId);

        TransportUserCardDTO obj = new TransportUserCardDTO();
        obj.setId(id);
        obj.setCardValue(new BigDecimal(0));
        obj.setCardType(1);
        obj.setValidTimes(0);
        obj.setSurplusTimes(0);

        if (id > 0) {
            obj = userCardService.getById(id);
        }

        if (userId > 0) {
            TransportUserDTO userDTO = userService.getById(userId);
            if (userDTO != null) {
                obj.setUserId(userId);
                obj.setTrueName(userDTO.getTrueName());
            }
        }
        model.addAttribute("Obj", obj);

        return "basic/usercard/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, TransportUserCardDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            if (objDTO.getStopFlag() == null) {
                objDTO.setStopFlag(0);
            }

            //日期
            objDTO.setStartTime(DateConvertUtils.strToDate(objDTO.getStartTimeSr()));
            objDTO.setEndTime(DateConvertUtils.strToDate(objDTO.getEndTimeSr()));

            //会员开卡必须有会员Id
            if (objDTO.getUserId() == null || objDTO.getUserId() <= 0) {
                map = OperateCode.CompositionResult(map, -10, "此卡未绑定会员，请重新开卡！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            //新增时检验是否唯一
            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                TransportUserCardDTOQuery query = new TransportUserCardDTOQuery();
                query.setCardNo(objDTO.getCardNo());
                TransportUserCardDTO obj = userCardService.getByQuery(query);

                if (obj != null && obj.getId() > 0) {
                    //说明此记录已经存在，不能重复插入
                    map = OperateCode.CompositionResult(map, -10, "此卡号已存在，请重新输入！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setDeleteFlag(0);

                objDTO.setCardValue(new BigDecimal(0)); //只能通过充值入口进行充值
                objDTO.setCashValue(new BigDecimal(0));
                objDTO.setAddUpValue(new BigDecimal(0));
                objDTO.setGiveTimes(0);
                objDTO.setAddUpTimes(0);

                objDTO = userCardService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                objDTO.setCardNo(null);
                objDTO.setCardValue(null);

                Boolean isNext = userCardService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 79, objDTO.getId(), 2,
                    "更新会员卡信息",
                    FastJsonUtils.toJSONString(objDTO),
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(HttpServletRequest request, Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = userCardService.delete(id);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 79, id, 4,
                    "删除会员卡信息",
                    "记录删除：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(HttpServletRequest request, Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = userCardService.changeState(id, status);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 79, id == null ? 0 : id, 2,
                    "更新会员卡状态",
                    "记录状态更新" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 充值

    /**
     * 充值
     *
     * @param model
     * @param id    记录id
     * @return
     */
    @RequestMapping(value = "/rechargeCard", method = RequestMethod.POST)
    public String rechargeCard(Model model, Integer id) {
        id = (id == null ? 0 : id);

        if (id > 0) {
            // 获取充值卡信息
            TransportUserCardDTO obj = userCardService.getById(id);

            if (obj != null) {
                obj.setTrueName(modelService.getUserTrueName(obj.getUserId()));
            }

            model.addAttribute("CardObj", obj);
            model.addAttribute("tradeTimeSr", DateConvertUtils.dateToShortStr(new Date()));
            model.addAttribute("rechargeTypeList", RechargeTypeEnum.getEnumList());
            model.addAttribute("receiveWayList", ReceiveWayEnum.getEnumList());
        }

        return "basic/usercard/recharge-card-modal";
    }

    /**
     * 保存充值
     *
     * @param dto
     * @return
     */
    @RequestMapping(value = "/saveRecharge", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveRecharge(HttpServletRequest request, TransportUserCardLogDTO dto) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (StringUtils.isBlank(dto.getCardNo())) {
            //todo
            map.put("returnMessage", "充值卡号错误！");
            return map;
        }

        //设置日期
        dto.setTradeTime(DateConvertUtils.strToDate(dto.getTradeTimeSr()));
        dto.setStartTime(DateConvertUtils.strToDate("1990-01-01"));
        dto.setEndTime(DateConvertUtils.strToDate("1990-01-01"));
        dto.setOrderId("CZ" + GeneralUtils.GenTimestamp());
        dto.setTradeBody(RechargeTypeEnum.getEnumByKey(dto.getRechargeType()) + dto.getRechargeAmount() + "元");
        dto.setTradingNo("");
        dto.setTimes(0);
        dto.setTableId(0);
        dto.setRecordId(0);
        dto.setCardType(1);
        dto.setFrontTimes(0);
        dto.setInvoiceType(0);
        dto.setPreTradeTime(DateConvertUtils.strToDate("1990-01-01"));
        dto.setNotifyTime(DateConvertUtils.strToDate("1990-01-01"));
        dto.setStatus(1);
        dto.setRechargeRate(BigDecimal.ZERO);
        dto.setRateAmount(BigDecimal.ZERO);
        dto.setLastNum(BigDecimal.ZERO);
        dto.setThisNum(BigDecimal.ZERO);
        dto.setUseNum(BigDecimal.ZERO);
        dto.setdSign(0);

        //新增
        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        dto.setAdminId(curr_obj.getId());
        dto.setCreateTime(new Date());
        dto.setOpIp(IpUtils.getClientIp(request));
        dto.setBrowser("");

        //1. 获取充值卡信息
        TransportUserCardDTO obj = userCardService.getById(dto.getCardId());

        //2. 保存充值记录
        dto = cardLogService.insert(dto);

        if (dto.getId() > 0) {

            //3. 更新充值卡金额
            TransportUserCardDTO query = new TransportUserCardDTO();
            query.setId(obj.getId());
            if (dto.getRechargeType() == 1) {
                query.setCardValue(obj.getCardValue().add(dto.getRechargeAmount()));      //充值
            } else {
                query.setCardValue(obj.getCardValue().subtract(dto.getRechargeAmount())); //扣款
            }
            userCardService.updateInfoById(query);

            map.put("returnCode", 1);
            map.put("returnMessage", "操作成功！");

        } else {
            map.put("returnMessage", "操作失败！");
        }

        //region *** 更新信息完毕记录操作日志 ***
        logService.insertSimple(1, 79, dto.getId(), 2,
                "更新会员卡充值信息",
                FastJsonUtils.toJSONString(dto),
                curr_obj.getId(),
                IpUtils.getClientIp(request),
                SystemUtils.getBrowserInfo(request));
        //endregion

        return map;
    }

    /**
     * 获取充值记录
     *
     * @param model
     * @param cardId 充值卡ID
     * @return
     */
    @RequestMapping(value = "/getCardRecord", method = RequestMethod.POST)
    public String getCardRecord(Model model, Integer cardId) {
        cardId = (cardId == null ? 0 : cardId);

        if (cardId > 0) {
            //充值记录
            TransportUserCardLogDTOQuery query = new TransportUserCardLogDTOQuery();
            query.setCardId(cardId);
            query.setPageSize(20);
            query.setOrderBy("order by id desc");
            Page<TransportUserCardLogDTO> record_page = cardLogService.getForPage(query);

            if (record_page != null && record_page.getItems().size() > 0) {
                for (TransportUserCardLogDTO item : record_page.getItems()) {
                    item.setTrueName(modelService.getUserTrueName(item.getUserId()));
                    item.setAdminName(modelService.getManageName(item.getAdminId()));

                    // 充值类型
                    item.setRechargeTypeName(RechargeTypeEnum.getEnumByKey(item.getRechargeType()));
                }
            }

            model.addAttribute("record_page", record_page);
        }

        return "basic/usercard/card-record-modal";
    }

    //endregion

}